<template>
  <div class="dashboard">
    <!-- 页面头部 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="welcome-section">
          <h1>
            <el-icon class="header-icon"><DataBoard /></el-icon>
            数据仪表盘
          </h1>
          <p class="welcome-text">
            欢迎回来，<span class="username">{{ userStore.userInfo?.nickname || '管理员' }}</span>！
            今天是 {{ formatDate(new Date()) }}
          </p>
        </div>
        <div class="quick-actions">
          <el-button type="primary" @click="$router.push('/news/create')">
            <el-icon><Plus /></el-icon>
            创建新闻
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon news-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.totalNews }}</h3>
              <p>总新闻数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon published-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.publishedNews }}</h3>
              <p>已发布</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon draft-icon">
              <el-icon><Edit /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.draftNews }}</h3>
              <p>草稿</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon views-icon">
              <el-icon><View /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.totalViews }}</h3>
              <p>总浏览量</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="content-row">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新新闻</span>
              <el-button type="primary" size="small" @click="$router.push('/news')">
                查看全部
              </el-button>
            </div>
          </template>
          
          <el-table :data="recentNews" style="width: 100%">
            <el-table-column prop="title" label="标题" show-overflow-tooltip />
            <el-table-column prop="categoryName" label="分类" width="100" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag
                  :type="getStatusType(row.status)"
                  size="small"
                >
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="viewCount" label="浏览量" width="80" />
            <el-table-column prop="gmtCreate" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.gmtCreate) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>快捷操作</span>
          </template>
          
          <div class="quick-actions">
            <el-button
              type="primary"
              icon="Plus"
              size="large"
              class="action-button"
              @click="$router.push('/news/create')"
            >
              创建新闻
            </el-button>
            
            <el-button
              type="success"
              icon="Collection"
              size="large"
              class="action-button"
              @click="$router.push('/categories')"
            >
              管理分类
            </el-button>
            
            <el-button
              type="info"
              icon="DataAnalysis"
              size="large"
              class="action-button"
              @click="handleAnalytics"
            >
              数据分析
            </el-button>
          </div>
        </el-card>
        
        <el-card style="margin-top: 20px;">
          <template #header>
            <span>系统信息</span>
          </template>
          
          <div class="system-info">
            <div class="info-item">
              <span class="label">当前用户：</span>
              <span class="value">{{ userStore.userInfo?.nickname }}</span>
            </div>
            <div class="info-item">
              <span class="label">用户角色：</span>
              <span class="value">{{ userStore.userInfo?.role === 'ADMIN' ? '管理员' : '普通用户' }}</span>
            </div>
            <div class="info-item">
              <span class="label">登录时间：</span>
              <span class="value">{{ formatDate(new Date()) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getNewsList } from '@/api/news'
import { Document, Check, Edit, View, DataBoard, Plus, Refresh } from '@element-plus/icons-vue'

// 状态管理
const userStore = useUserStore()

// 响应式数据
const stats = reactive({
  totalNews: 0,
  publishedNews: 0,
  draftNews: 0,
  totalViews: 0
})

const recentNews = ref([])

// 获取统计数据
const fetchStats = async () => {
  try {
    // 获取所有新闻
    const allNews = await getNewsList({ page: 1, size: 100 })
    stats.totalNews = allNews.count || 0
    
    // 获取已发布新闻
    const publishedNews = await getNewsList({ page: 1, size: 100, status: 1 })
    stats.publishedNews = publishedNews.count || 0
    
    // 获取草稿新闻
    const draftNews = await getNewsList({ page: 1, size: 100, status: 0 })
    stats.draftNews = draftNews.count || 0
    
    // 计算总浏览量
    stats.totalViews = allNews.results?.reduce((total, news) => total + (news.viewCount || 0), 0) || 0
    
    // 获取最新新闻（前5条）
    recentNews.value = allNews.results?.slice(0, 5) || []
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',     // 草稿
    1: 'success',  // 已发布
    2: 'warning'   // 已归档
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '已归档'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 处理数据分析
const handleAnalytics = () => {
  ElMessage.info('数据分析功能开发中...')
}

// 刷新数据
const refreshData = () => {
  fetchStats()
  ElMessage.success('数据已刷新')
}

// 生命周期
onMounted(() => {
  fetchStats()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面头部 */
.dashboard-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px 0;
  margin-bottom: 30px;
  border-radius: 0 0 20px 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.welcome-section h1 {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 36px;
}

.welcome-text {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

.username {
  font-weight: 600;
  color: #ffd700;
}

.quick-actions {
  display: flex;
  gap: 12px;
}

.quick-actions .el-button {
  border-radius: 25px;
  padding: 12px 24px;
  font-weight: 500;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.news-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.published-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.draft-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.views-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info h3 {
  margin: 0 0 5px 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-info p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.content-row {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.action-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
}

.system-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #909399;
  font-size: 14px;
}

.value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}
</style>
